/*
 * Created by SharpDevelop.
 * User: rseward
 * Date: 6/4/2008
 * Time: 5:22 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Data;
using System.Collections.Generic;
using log4net;

using RD.Metadata.Database.Sql;


using AvvaMobileNHibernateHelperKit.Framework;
using AvvaMobileNHibernateHelperKit.NHibernate;

namespace AvvaMobileNHibernateHelperKit
{
	/// <summary>
	/// Description of ConfigFileGenerator.
	/// </summary>
	public class HbmXmlFileGenerator
	{
		#region log4net
		protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion
		
		private Data dataClass;
		private MainForm form;
		private Project project;
		private bool dynamicUpdate;
		
		
		public bool DynamicUpdate {
			get { return dynamicUpdate; }
			set { dynamicUpdate = value; }
		}
		
		
		public HbmXmlFileGenerator(MainForm form, Data dataClass, Project project)
		{
			this.form = form;
			this.dataClass = dataClass;
			this.project = project;
		}
		
		public void GenerateFiles()
		{
			form.Progress("Config files writing", 70);
			log.Debug("Config files writing");

			foreach (string tableName in project.SelectedTables) {
				string className = project.NameFormatter.GetClassName(tableName) ;
				System.IO.StreamWriter hbmSw = new System.IO.StreamWriter( project.ProjectDir+ @"\App_Code\NHMappings\" + className + ".hbm.xml");
				//DataTable dt = dataClass.GetTableColumnsInfo("EXEC dbo.sp_MShelpcolumns '" + tableName + "'");

				SqlMetaTable tabMeta = dataClass.GetTableInfo(tableName);
				
				if (tabMeta == null) {
					throw new Exception("Unable to find meta data for "+tableName);
				}
				
				/*
        		if (tabMeta!=null) {
        			log.Debug("Meta info about tableName="+tableName+" has the following meta columns");
        			foreach (SqlMetaColumn col in tabMeta.Columns) {
        				log.Debug("Tab Meta Data: "+col.ColumnName+" "+col.DbType+" PK="+col.IsPrimaryKey);
        			}
        		} else {
        			log.Debug("Meta data for tableName="+tableName+" was not loaded");
        		} */
				

				hibernatemapping hmapping = new hibernatemapping();
				
				hmapping.defaultcascade = cascadeStyle.none;
				
				NHibernate.@class clazz = new NHibernate.@class();
				
				clazz.dynamicupdate=this.dynamicUpdate;
				clazz.name = project.Namespace+"."+className+", "+project.AssemblyName;
				clazz.table = tableName;
				
				hmapping.Items = new object[] { clazz };
				
				/*
        		hbmSw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        		hbmSw.WriteLine("<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\">");

        		string dynamicUpdateStr = "";
        		if (dynamicUpdate) { dynamicUpdateStr = "dynamic-update=\"true\""; }
        		hbmSw.WriteLine("<class name=\"" + project.Namespace + "." + className + ", " + project.AssemblyName + "\" table=\"" + tableName + "\" " + dynamicUpdateStr + ">");

				 */
				List<NHibernate.property> propList = new List<NHibernate.property>();
				log.Debug("table_name="+tableName);
				foreach (SqlMetaColumn col in tabMeta.Columns)
				{
					string colName = col.ColumnName;
					string propName = project.NameFormatter.GetPropertyName( className, colName);
					
					if (col.IsPrimaryKey)
					{
						NHibernate.id idTag = project.DbDriver.GetHbmPrimaryKeyProperty(col, propName, colName);
						
						if (idTag!=null) {
							clazz.Item1 = idTag;
						}
						
					} else {
						NHibernate.property propTag = project.DbDriver.GetHbmFieldProperty(col, propName, colName);
						
						if (propTag!=null) {
							propList.Add( propTag);							
						}
					}
				}
				clazz.Items = propList.ToArray();

				// TODO: how to interject a GeneratedBy comment?
				hbmSw.WriteLine( XmlUtils.Write( hmapping ) );
				
				hbmSw.Flush();
				hbmSw.Close();
				hbmSw.Dispose();
				
			}

			form.Progress("Config files generated", 100);
			
		}
	}
}
